package com.ruihui.activity.controller;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.ruihui.activity.exceprion.GetException;
import com.ruihui.activity.pojo.Accoupon;
import com.ruihui.activity.pojo.Acgoods;
import com.ruihui.activity.service.AccouponService;
import com.ruihui.activity.util.ConstantHolder;
import com.ruihui.activity.util.Result;
import com.ruihui.activity.util.ResultCode;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

/**
 * 活动优惠券
 * 
 * @author cf
 *
 */
@Api(tags = "活动优惠券前台")
@RestController
@RequestMapping("/webPonActive")
public class WebActivePonController {
	private static final Logger log = LoggerFactory.getLogger(WebActivePonController.class);

	@Autowired
	private StringRedisTemplate redisTemplate;
	@Autowired
	private Redisson redisson;
	@Autowired
	private AccouponService accouponService;

	@ApiOperation(value = "获取用户优惠券信息", response = Accoupon.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "sessionid", value = "sessionidid", required = true, paramType = "query"),
			@ApiImplicitParam(name = "state", value = "0：可使用，1：暂不可使用，2：已使用，3：已过期,4：未过期", required = false, paramType = "query"),
			@ApiImplicitParam(name = "type", value = "1金额，2折扣", required = false, paramType = "query"),
			@ApiImplicitParam(name = "id", value = "优惠券id（优惠券表id）", required = false, paramType = "query"),
			@ApiImplicitParam(name = "gas", value = "组合[{'cid':6,'acrdprice':55},{'cid':5,'acrdprice':25}]（cid=-1为通用优惠券）", required = false, paramType = "query"), })
	@PostMapping("/accouponlist")
	public Object accouponlist(String sessionid, Integer state, Integer type, Integer id, String gas) {

		try {
			List<Accoupon> lists = new ArrayList<Accoupon>();
			List<Accoupon> ga = JSON.parseArray(gas, Accoupon.class);

			if (!StringUtils.isEmpty(sessionid)) {
				String ob = (String) redisTemplate.opsForValue().get(sessionid);
				Integer memberId = ob == null ? null : Integer.valueOf(ob);
				if (memberId == null) {
					return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
				}
				if (ga == null || ga.isEmpty() || ga.size() == 0) {
					return Result.success(accouponService.getAccoupons(memberId, state, type, id, null, null));
				} else {
					ga.stream().forEach(map -> {
						Integer catid = (map.getCid() == null) ? -2 : Integer.parseInt(String.valueOf(map.getCid()));
						BigDecimal acrdprices = new BigDecimal(String.valueOf(map.getAcrdprice()));
						List<Accoupon> list = accouponService.getAccoupons(memberId, state, type, id, catid,
								acrdprices);
						lists.addAll(list);
					});
				}
			} else {
				return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
			}
			return Result.success(lists);
		} catch (Exception e) {
			return GetException.getCatch(e, log);
		}
	}

	@ApiOperation(value = "用户领取优惠券", response = Accoupon.class)
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "优惠券id", required = true, paramType = "query"),
			@ApiImplicitParam(name = "gnum", value = "领取数量", required = false, paramType = "query"),
			@ApiImplicitParam(name = "sessionid", value = "sessionid", required = false, paramType = "query") })
	@PostMapping("/getAccoupon")
	public Object getAccoupon(@RequestParam Integer id, @RequestParam Integer gnum, String sessionid) {
		Integer memberId = null;
		int code = 0;
		boolean flag = false;
		try {
			String lockKey = String.format(ConstantHolder.LOCK, id);
			RLock lock = redisson.getFairLock(lockKey);
			if (!StringUtils.isEmpty(sessionid)) {
				String ob = (String) redisTemplate.opsForValue().get(sessionid);
				memberId = ob == null ? null : Integer.valueOf(ob);
				if (memberId == null) {
					return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
				}
			} else {
				return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
			}
			// 领取优惠券
			try {
				flag = lock.tryLock(5, 30, TimeUnit.SECONDS);
				if (flag) {
					code = accouponService.getRedAccoupon(id, memberId, gnum);
				}
			} finally {
				lock.unlock();
			}

			if (code == 1) {
				return Result.success();
			}

			return Result.error();
		} catch (Exception e) {
			return GetException.getCatch(e, log);
		}
	}

	@ApiOperation(value = "验证优惠券是否在活动期间", response = Acgoods.class)
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "优惠券id（活动商品表的id）", required = true, paramType = "query") })
	@PostMapping("/iniacpGoods")
	public Object iniacpGoods(@RequestParam Integer id) {
		try {
			Acgoods ac = accouponService.iniacGoods(id);
			if (!StringUtils.isEmpty(ac)) {
				return Result.success(ac);
			}
			return Result.error();
		} catch (Exception e) {
			return GetException.getCatch(e, log);
		}
	}

	@ApiOperation(value = "用户使用优惠券更新状态")
	@ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "优惠券id（优惠券表id）", required = true, paramType = "query"),
			@ApiImplicitParam(name = "sessionid", value = "sessionid", required = true, paramType = "query"), })
	@PostMapping("/updPon")
	public Object updPon(@RequestParam Integer id, @RequestParam String sessionid) {
		Integer memberId = null;
		Accoupon accoupon = new Accoupon();
		try {

			if (!StringUtils.isEmpty(sessionid)) {
				String ob = (String) redisTemplate.opsForValue().get(sessionid);
				memberId = ob == null ? null : Integer.valueOf(ob);
				if (memberId == null) {
					return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
				}
			} else {
				return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
			}
			// 获取用户可使用优惠券
			List<Accoupon> accoupons = accouponService.getAccoupons(memberId, 0, null, id, null, null);
			if (!accoupons.isEmpty() && accoupons.size() == 1) {
				accoupon = accoupons.get(0);
				accoupon.setState(2);
				boolean flag = accouponService.updateById(accoupon);
				if (flag) {
					Result.success();
				}
				return Result.errorMsg("更新状态 失败");
			} else {
				return Result.errorMsg("优惠券过期");
			}

		} catch (Exception e) {
			return GetException.getCatch(e, log);
		}
	}

	// @ApiOperation(value = "test")
	// @ApiImplicitParams({ @ApiImplicitParam(name = "id", value = "优惠券id",
	// required = false, paramType = "query") })
	// @PostMapping("/test")
	// public Object test(@RequestParam Integer id) {
	// Preconditions.checkArgument(id>0, "id不能为空");
	// return id;
	// }

}
